package com.alex.taskmanager.dao.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class JdbcUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(JdbcUtils.class);
	
	public static void closeResultSet(ResultSet resultSet) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				LOGGER.warn(e.getMessage(), e);
			}
		}
	}
	
	public static void closeConnection(Connection connection) {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				LOGGER.warn(e.getMessage(), e);
			}
		}
	}
	
	public static void closePreparedStatement(PreparedStatement ps) {
		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				LOGGER.warn(e.getMessage(), e);
			}
		}
	}
	
	public static int getGeneratedKey(PreparedStatement ps) throws SQLException {
		ResultSet resultSet = null;
		try {
			resultSet = ps.getGeneratedKeys();
			resultSet.next();
			return resultSet.getInt(1);
		} finally {
			closeResultSet(resultSet);
		}
	}
}
